<template>
  <van-button
            v-if="isFollowed"
            class="follow-btn"
            round
            size="small"
            @click="onFollow"
            :loading="loading"
          >已关注</van-button>

          <van-button
            v-else
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            @click="onFollow"
            :loading="loading"
          >关注</van-button>
</template>

<script>
import { ref } from 'vue'
import { Toast } from 'vant'
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  props: {
    isFollowed: { // 是否关注
      type: Boolean,
      required: true
    },
    userId: { // 作者id
      type: [Number, String],
      required: true
    }
  },
  setup (props, context) {
    const loading = ref(false)// 关注按钮是否加载
    async function onFollow () {
      loading.value = true
      try {
        if (props.isFollowed) {
        // 取关
          await deleteFollow(props.userId)
          // article.data.is_followed = false
          context.emit('deleteFollow')
        } else {
        // 关注
          await addFollow(props.userId)
          // article.data.is_followed = true
          context.emit('addFollow')
        }
      } catch (err) {
        if (err.response && err.response.status === 400) {
          Toast('不能关注自己')
        } else if (err.response && err.response.status === 401) {
          Toast('请先登录')
        } else {
          Toast('操作失败')
        }
      }
      loading.value = false
    }
    return {
      loading,
      onFollow
    }
  }
}
</script>

<style>

</style>
